package homework;

import java.util.Locale;
import java.util.Scanner;

/**
 * @author DCSGO
 * @version 1.0
 * (1)在main方法中启动两个线程
 * (2)第1个线程循环随机打印100以内的整数
 * (3)直到第2个线程从键盘读取了“Q”命令。
 */
public class Homework01 {
    public static void main(String[] args) {
        PutRandomNum A = new PutRandomNum();
        Thread putRandomNum = new Thread(A);
        Thread getKey = new Thread(new GetKey(A));

        getKey.start();
        putRandomNum.start();
        /*
         * 14
         * 请输入指令(Q退出)：
         * 81
         * 24
         * 78
         * Q
         * GetKey 已退出
         * PutRandomNum 已退出
         *
         * 进程已结束，退出代码为 0
         */
    }
}

class PutRandomNum implements Runnable {
    private boolean loop = true;

    public void setLoop(boolean loop) {
        this.loop = loop;
    }

    @Override
    public void run() {
        while (loop) {
            System.out.println((int) (Math.random() * 100) + 1);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("PutRandomNum 已退出");
    }
}

class GetKey implements Runnable {
    private PutRandomNum putRandomNum;

    public GetKey(PutRandomNum putRandomNum) {
        this.putRandomNum = putRandomNum;
    }

    @Override
    public void run() {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("请输入指令(Q退出)：");
            char putin = scanner.next().toUpperCase().charAt(0);
            if (putin == 'Q') {
                putRandomNum.setLoop(false);
                System.out.println("GetKey 已退出");
                break;
            }
        }
    }
}
